package leetcode.f1t100;

import leetcode.struct.TreeNode;

import java.util.Stack;

/**
 * 搜索二叉树有两个点位置交换了, 现在需要交换回来
 * https://leetcode.com/problems/recover-binary-search-tree
 *
 * @author lichx
 * @createTime 2024/2/22 14:55
 */
public class Q99_RecoverBinarySearchTree {

    public void recoverTree(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null, first = null, second=null;
        while(root != null || !stack.isEmpty()) {
            while(root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(pre != null && pre.val > root.val){
                if(first == null) {
                    first = pre;
                }
                second = root;
            }
            pre = root;
            root = root.right;
        }
        int temp = first.val;
        first.val = second.val;
        second.val = temp;
    }
}
